package com.cskaoyan.service;

import com.cskaoyan.bean.bo.cartbo.CartCheckedBO;
import com.cskaoyan.bean.bo.cartbo.CartCreateBO;
import com.cskaoyan.bean.bo.cartbo.CartIdsBO;
import com.cskaoyan.bean.bo.cartbo.CartUpdateBO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.cartvo.CartIndexVO;
import com.cskaoyan.bean.vo.cartvo.CartOrderVO;
import com.cskaoyan.bean.vo.cartvo.CartTotalBean;
import com.cskaoyan.bean.vo.cartvo.CheckedAddress;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.System;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @param
 * @Date: 2022/6/7 11:13
 * @Description:购物车服务实现类
 * @Author: 李宇浩
 * @return
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsProductMapper productMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    /**
     * 购物车商品数量红点回显
     */
    @Override
    public int goodsCount(String username) {

        int id = userMapper.selectIdByUsername(username);

        int count = cartMapper.querryCountByUserId(id);

        return count;
    }

    /**
     * 添加购物车
     * 返回购物车商品数量
     */
    @Override
    public int addCart(CartCreateBO cartCreateBO, String username) {

        Goods goods = goodsMapper.selectByPrimaryKey(cartCreateBO.getGoodsId());
        GoodsProduct goodsProduct = productMapper.selectByPrimaryKey(cartCreateBO.getProductId());
        int id = userMapper.selectIdByUsername(username);
        Cart cart = new Cart();

        // 封装购物车数据
        // 校验库存，如果库存为0则不添加商品，返回404
        if (goodsProduct.getNumber() - cartCreateBO.getNumber() < 0) {
            return 404;
        }
        cart.setUserId(id);
        cart.setGoodsId(goods.getId());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setProductId(goodsProduct.getId());
        cart.setPrice(goodsProduct.getPrice());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(true);
        cart.setPicUrl(goodsProduct.getUrl());
        cart.setAddTime(new Date(System.currentTimeMillis()));
        cart.setUpdateTime(new Date(System.currentTimeMillis()));
        cart.setDeleted(false);


        // 新增购物车数据,如果购物车已存在此订单则只更新数量
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andGoodsIdEqualTo(cart.getGoodsId());
        criteria.andGoodsSnEqualTo(cart.getGoodsSn());
        criteria.andGoodsNameEqualTo(cart.getGoodsName());
        criteria.andProductIdEqualTo(cart.getProductId());
        criteria.andSpecificationsEqualTo(cart.getSpecifications());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        if (!carts.isEmpty()) {
            Cart cart1 = carts.get(0);
            Short number = cart1.getNumber();
            Integer cartId = cart1.getId();
            Integer newNum = number + cartCreateBO.getNumber();
            cart.setId(cartId);
            cart.setNumber(Short.valueOf(String.valueOf(newNum)));
            cartMapper.updateByPrimaryKeySelective(cart);
        } else {
            cart.setNumber(cartCreateBO.getNumber());
            cartMapper.insert(cart);
        }

        // 返回用户订单数据
        int count = goodsCount(username);
        return count;
    }

    /**
     * 购物车列表展示
     */
    @Override
    public CartIndexVO getIndex(String username) {

        int id = userMapper.selectIdByUsername(username);
        // 获取购物车商品总量
        Integer count = cartMapper.countGoodsByUserId(id);
        if (count == null) {
            count = 0;
        }
        // 获取购物车被选中的商品总量
        Integer checkedCount = cartMapper.countCheckedGoodsByUserId(id);
        if (checkedCount == null) {
            checkedCount = 0;
        }
        // 获取购物车商品总价
        Double amount = cartMapper.countGoodsAmountByUserId(id);
        if (amount == null) {
            amount = 0.0;
        }
        // 获取购物车被选中的商品总价
        Double checkedAmount = cartMapper.countCheckedAmountByUserId(id);
        if (checkedAmount == null) {
            checkedAmount = 0.0;
        }

        // 获取购物车所有商品详细信息
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        CartIndexVO cartIndexVO = new CartIndexVO();
        CartTotalBean cartTotalBean = new CartTotalBean();
        cartTotalBean.setGoodsCount(count);
        cartTotalBean.setCheckedGoodsCount(checkedCount);
        cartTotalBean.setGoodsAmount(amount);
        cartTotalBean.setCheckedGoodsAmount(checkedAmount);
        cartIndexVO.setCartTotal(cartTotalBean);
        cartIndexVO.setCartList(carts);

        return cartIndexVO;
    }

    /**
     * 购物车数据更新
     * 返回参数
     * 404：库存溢出
     * 200：更新成功
     */
    @Override
    public int updateCart(CartUpdateBO cartUpdateBO) {
        GoodsProduct goodsProduct = productMapper.selectByPrimaryKey(cartUpdateBO.getProductId());
        // 库存不足直接返回
        if (goodsProduct.getNumber() - cartUpdateBO.getNumber() < 0) {
            return 404;
        }

        // 更新订单库存
        cartMapper.updateNumberById(cartUpdateBO.getId(), cartUpdateBO.getNumber());

        return 200;
    }

    /**
     * 商品选中状态更新
     */
    @Override
    public CartIndexVO checked(CartCheckedBO checkedBO, String username) {

        // 更新选中状态
        for (Integer productId : checkedBO.getProductIds()) {
            Boolean isChecked = checkedBO.getIsChecked();
            Integer checked = isChecked == true ? 1 : 0;
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andProductIdEqualTo(productId);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            for (Cart cart : carts) {
                cartMapper.updateCheckById(cart.getId(), checked);
            }
        }

        // 获取并返回新的商品展示列
        CartIndexVO cartIndexVO = getIndex(username);

        return cartIndexVO;
    }

    /**
     * 快速增加订单(点击购买弹出)
     * 返回参数
     * 404：库存不足
     * 订单id：添加成功
     */
    @Override
    public int fastAdd(CartCreateBO cartCreateBO, String username) {

        Goods goods = goodsMapper.selectByPrimaryKey(cartCreateBO.getGoodsId());
        GoodsProduct goodsProduct = productMapper.selectByPrimaryKey(cartCreateBO.getProductId());
        int id = userMapper.selectIdByUsername(username);
        Cart cart = new Cart();

        // 封装购物车数据
        // 校验库存，如果库存为0则不添加商品，返回404
        if (goodsProduct.getNumber() - cartCreateBO.getNumber() < 0) {
            return 404;
        }
        cart.setNumber(cartCreateBO.getNumber());
        cart.setUserId(id);
        cart.setGoodsId(goods.getId());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setProductId(goodsProduct.getId());
        cart.setPrice(goodsProduct.getPrice());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(false);
        cart.setPicUrl(goodsProduct.getUrl());
        cart.setAddTime(new Date(System.currentTimeMillis()));
        cart.setUpdateTime(new Date(System.currentTimeMillis()));
        cart.setDeleted(false);


        // 新增购物车数据
        cartMapper.insertAndFetchId(cart);

        return cart.getId();
    }

    /**
     * 购物车删除
     */
    @Override
    public CartIndexVO delete(CartIdsBO cartIdsBO, String username) {
        int id = userMapper.selectIdByUsername(username);
        // 删除操作
        for (Integer productId : cartIdsBO.getProductIds()) {
            cartMapper.updateDeleteById(productId, id);
        }

        CartIndexVO cartIndexVO = getIndex(username);
        return cartIndexVO;
    }

    /**
     * 订单修改界面回显
     */
    @Override
    public CartOrderVO getCartOrder(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId) {

        // 获取user信息
        Subject subject = SecurityUtils.getSubject();
        User primaryPrincipal = (User) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();

        // 展示类
        CartOrderVO cartOrderVO = new CartOrderVO();


        // 优惠券处理
        BigDecimal discount = new BigDecimal("0");
        if (couponId != -1 && couponId != 0) {
            Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
            // 折扣价格
            discount = coupon.getDiscount();
        }

        // 团购处理
        BigDecimal grouponDiscount = new BigDecimal("0");
        if (grouponRulesId != -1 && grouponRulesId != 0) {
            grouponDiscount = grouponRulesMapper.selectByGoodsId(grouponRulesId);
        }

        // 运费
        String freightPrice = cartOrderVO.getFreightPrice();

        // 查询条件
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        List<Cart> carts = new LinkedList<>();
        String goodsTotalPrice = "0";
        String orderTotalPrice = "0";
        String actualPrice = "0";
        // 如果cartId参数为0则为展示所有勾选物品，不为0则是配合fastadd使用的方法
        if (cartId == 0) {
            criteria.andUserIdEqualTo(id);
            criteria.andCheckedEqualTo(true);
            criteria.andDeletedEqualTo(false);
            carts = cartMapper.selectByExample(cartExample);

            // 计算商品总价
            BigDecimal sum = BigDecimal.ZERO;
            for (Cart cart : carts) {
                BigDecimal price = cart.getPrice();
                BigDecimal numb = BigDecimal.valueOf((int) cart.getNumber());
                BigDecimal multiply = price.multiply(numb);
                sum = sum.add(multiply);
            }
            goodsTotalPrice = sum.toString();
            orderTotalPrice = sum.add(BigDecimal.valueOf(Integer.parseInt(freightPrice))).toString();
            actualPrice = sum.add(BigDecimal.valueOf(Integer.parseInt(freightPrice))).subtract(discount).subtract(grouponDiscount).toString();
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            carts.add(cart);
            goodsTotalPrice = cart.getPrice().toString();
            orderTotalPrice = cart.getPrice().add(BigDecimal.valueOf(Integer.parseInt(freightPrice))).toString();
            actualPrice = cart.getPrice().add(BigDecimal.valueOf(Integer.parseInt(freightPrice))).subtract(discount).subtract(grouponDiscount).toString();
        }

        // 实际价格小于0则置0
        if (actualPrice.indexOf("-") != -1) {
            actualPrice = "0";
        }

        // 展示类参数处理
        // 地址参数封装
        Address address = addressMapper.selectByPrimaryKey(addressId);
        CheckedAddress checkedAddress = null;
        if (address != null) {
            checkedAddress = new CheckedAddress();
            checkedAddress.setId(addressId);
            checkedAddress.setName(address.getName());
            checkedAddress.setUserId(address.getUserId());
            checkedAddress.setProvince(address.getProvince());
            checkedAddress.setCity(address.getCity());
            checkedAddress.setCounty(address.getCounty());
            checkedAddress.setAddressDetail(address.getAddressDetail());
            checkedAddress.setAreaCode(address.getAreaCode());
            checkedAddress.setTel(address.getTel());
            checkedAddress.setIsDefault(address.getIsDefault());
            checkedAddress.setAddTime(address.getAddTime());
            checkedAddress.setUpdateTime(address.getUpdateTime());
            checkedAddress.setDeleted(address.getDeleted());
        }

        // 展示类封装
        cartOrderVO.setCartId(cartId);
        cartOrderVO.setAddressId(addressId);
        cartOrderVO.setCouponId(couponId);
        cartOrderVO.setUserCouponId(userCouponId);
        cartOrderVO.setGrouponRulesId(grouponRulesId);
        cartOrderVO.setGrouponPrice(grouponDiscount.toString());
        cartOrderVO.setCouponPrice(discount.toString());
        cartOrderVO.setGoodsTotalPrice(goodsTotalPrice);
        cartOrderVO.setOrderTotalPrice(orderTotalPrice);
        cartOrderVO.setActualPrice(actualPrice);
        if (couponId != -1) {
            cartOrderVO.setAvailableCouponLength(1);
        } else {
            cartOrderVO.setAvailableCouponLength(0);
        }
        cartOrderVO.setCheckedAddress(checkedAddress);
        cartOrderVO.setCheckedGoodsList(carts);

        return cartOrderVO;
    }
}
